package com.totem.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.totem.admin.mapper.TIssuesMapper;
import com.totem.admin.model.TIssueUrl;
import com.totem.admin.model.TIssues;
import com.totem.admin.service.ITIssueService;
import com.totem.admin.service.ITIssueUrlService;
import com.totem.admin.vo.SubmitIssueVO;
import com.totem.base.constants.ErrorCode;
import com.totem.base.exception.BaseException;
import com.totem.base.mybatis.UserIdContext;
import com.totem.customer.mapper.TCustomerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class TIssueServiceImpl extends ServiceImpl<TIssuesMapper, TIssues> implements ITIssueService {
    @Autowired
    private TCustomerMapper tCustomerMapper;
    @Autowired
    private ITIssueUrlService itIssueUrlService;

    @Override
    public boolean save(SubmitIssueVO vo) {
        Long customerId = UserIdContext.getUserId();
        if(customerId==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        TIssues tIssues = TIssues.builder()
                .issue(vo.getIssue())
                .build();
        int effect = baseMapper.insert(tIssues);

        boolean result = effect>0;
        if(result && !CollectionUtils.isEmpty(vo.getIssueUrlList())) {
            List<TIssueUrl> issueUrlList = new ArrayList<>();
            for(String url : vo.getIssueUrlList()) {
                TIssueUrl tIssueUrl = TIssueUrl.builder()
                        .issueId(tIssues.getId())
                        .issueUrl(url)
                        .build();
                issueUrlList.add(tIssueUrl);
            }
            result = itIssueUrlService.saveBatch(issueUrlList);
        }
        return result;
    }
}
